#!/usr/bin/perl

#    VGAP Thingy CIC Data Collection Script
#    Copyright (C) 2004 Peter Burns
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License version 2 as
#    published by the Free Software Foundation.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#    This program is currently hosted at http://code.google.com/p/vgapd/

use warnings;
use strict;
use English;

$main::TZ='EST5EDT';
use Date::Manip;
use Config::IniFiles;
use DBI;
use VGAP::Tools;
use Pod::Usage;
use Getopt::Long;
use File::Spec;

## DB Variables
## These are defaults and can be overridden via the command line parameters
my %opts;
my $opts{dbserver} = "localhost";
my $opts{dbport} = "3306";
my $opts{dbname} = "vgap";
my $opts{dbdriver} = "mysql";
my $opts{dbuser} = "vgapd";
my $opts{dbpass} = "vgapd";

## Variables
my $version = "0.1";
my $turn;
my %gameini;
my $dbh;
my $GameINIfile;
my $DebugLog = 8;
my $DebugCon = 1;
my $logfile;


## Subroutines

sub logit($@) {
   my $level = shift;
   my $now = UnixDate('today',"%c");
   my @logentry = @_;


   if (!defined($logfile)) {
      die("The logfile variable has not been defined!\n");
   }

   if ($level <= $DebugLog) {
      open FILE,">>$logfile" or warn("Can't open LogFile $logfile because $!");
      print FILE "[$now], LEVEL=$level : ",@logentry,"\n";
      close FILE;
   }

   if ($level <= $DebugCon) {
      print "[$now] : ",@logentry,"\n";
   }
} #End sub logit


sub GetGameID() {
	my @row;
	
	$sth = $dbh->prepare("SELECT GameID FROM Games WHERE GameINI=?");
	$sth->execute($GameINIfile);
	@row = $sth->fetchrow_array;
	return $row[0];
} # end sub GetGameID()

sub UpdateRaceNames($) {
	my $GameID = shift;
	my @shortnames = GetRaceShortNames($gameini{General}{Homedir});
	my @longnames = GetRaceLongNames($gameini{General}{Homedir});
	my @adjectives = GetRaceAdjectiveNames($gameini{General}{Homedir});
	my $count = 0;

	$sth = $dbh->prepare("UPDATE Races SET LongName=?, ShortName=?, Adjective=? WHERE GameID=? and PlayerID=?");
	foreach (@longnames) {
		$sth->execute($longnames[$count], $shortnames[$count], $adjectives[$count], $GameID, $count+1);
		$count++;
	}
	
}

sub UpdateGameData() {
  my $GameID;

  $turn = GetTurnNumber($gameini{General}{Homedir});
  logit(1,"Turn: $turn");  
  $GameID = GetGameID();
  logit(1,"GameID: $GameID");
  
  
} #End UpdateGameData sub

## Main Body Start

GetOptions(\%opts, "help", "version", "man", "dbserver", "dbport", "dbdriver", "dbname", "dbuser", "dbpass"))
	or pod2usage(-message => "Failed to parse the command line options!", -exitval => 2);

pod2usage(1) if $opts{help};
pod2usage(-verbose => 2) if $opts{man};
if ($opts{version}) {
	print "$0\n";
	print "VGAPd data collector\n";
	print "Version $version\n";
	print "(c) 2005, Peter Burns\n\n";
	exit;
}

pod2usage(-message => "No Game INI specified!", -exitval => 2) if !defined($ARGV[0]);
die("$ARGV[0] does not exist!\n") if (!-e $ARGV[0]);
die("$ARGV[0] is not readable!\n") if (!-r $ARGV[0]);
$GameINIfile = $ARGV[0];

tie %gameini, 'Config::IniFiles', ( -file => $GameINIfile )
  or die("Could not open Game ini file $GameINIfile\n");

$logfile = File::Spec->catfile($gameini{General}{Homedir}, "collect.log");

logit(0,"Connecting to database $opts{dbname} on $opts{dbserver}:$opts{dbport}");
$dbh = DBI->connect("dbi:$opts{dbdriver}:database=$opts{dbname};host=$opts{dbserver};port=$opts{dbport}",
                    $opts{dbuser},
                    $opts{dbpass},
                    { AutoCommit => 1 })
  or die $DBI::errstr;

UpdateGameData;

logit(0,"Disconnecting from database $opts{dbname} on $opts{dbserver}:$opts{dbport}");
$dbh->disconnect or warn $dbh->errstr;
untie %gameini;


__END__

=head1 NAME

collect.pl - script to insert score data into the database after each host run

=head1 SYNOPSIS

collect.pl [options] [/path/to/gameinifile ...]

=head1 OPTIONS

=over 8

=item B<--help>

Print a brief help message and exits.

=item B<--version>

Prints the version blurb and exits.

=item B<--man>

Prints the full man page and exits

=item B<--dbserver>=U<HOST>

Overide the database server to use, default is localhost

=item B<--dbdriver>=U<DBI-driver-name>

The name of the DBI driver to use, the default is mysql

=item B<--dbport>=U<PORT>

The port to connect to the database server on, the default is 3306

=item B<--dbname>=U<NAME>

The name of the database to use on the server, the default is vgap

=item B<--dbuser>=U<USER>

The user name to connect to the database with, the default is vgapd

=item B<--dbpass>=U<PASSWORD>

The password to use to connect to the database with, the default is vgapd

=back

=head1 DESCRIPTION

B<This program> will read a vgapd game ini file, and use the information contained in it to pull score and other info from the game files and insert them into the database.

If no game ini file name is provided as a command line parameter, the program will terminate.

The usual procedure is to run this script after each host run to update the database. It is recommended that you run it as a game hook in VGAPd.

=cut
